import { Component, OnChanges, OnInit, DoCheck, OnDestroy, SimpleChanges, ComponentFactoryResolver, ViewChild, ViewContainerRef, HostListener, ElementRef, Injector, ComponentRef, ReflectiveInjector, ApplicationRef } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';

export interface CanDraw {
  beforeLeave(): boolean | Promise<boolean>;
  beforeClose(): void;
}


@Component({
  selector: "drawer",
  template: `
   <div class="draw-container" [ngClass]="{'show':show}">
    <ng-template #componentContainer></ng-template>
   </div>
  `,
  styleUrls: ['./draw.component.css', '../../app.component.css']
})

export class DrawComponent implements OnChanges, OnInit, DoCheck, OnDestroy {
  instance: any;
  show;
  injectComponet;
  data;
  componentRef;
  beforeLeave;
  firstInit;
  closeResolve;
  @ViewChild("componentContainer", { read: ViewContainerRef }) container: ViewContainerRef;
  constructor(private router: Router, private resolver: ComponentFactoryResolver,
    private elementRef: ElementRef, private injector: Injector, private applicationRef: ApplicationRef) {
    this.show = false;
    this.firstInit = true;
  }

  @HostListener('document:click', ['$event'])
  onClick(event) {
    //第一次点击无效
    if (this.firstInit) {
      this.firstInit = false;
      return;
    }
    if (!this.elementRef.nativeElement.contains(event.target)) {
      let result = this.componentRef.instance.beforeLeave();
      if (typeof (result) == "boolean" && result) {
        this.closeComponent();
      }
      if (typeof (result) == "object" && result.then) {
        result.then(r => {
          if (r) {
            this.closeComponent();
          }
        })
      }
    }
  }

  private closeComponent() {
    this.show = false;
    setTimeout(() => {
      this.container.clear();
      this.closeResolve('close');
    }, 500);
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.show = true;
    });
  }
  ngOnDestroy(): void {
    this.container.clear();
  }
  ngDoCheck(): void {

  }
  ngOnInit(): void {
    this.container.clear();
    this.componentRef = this.container.createComponent(this.resolver.resolveComponentFactory(this.injectComponet));
    this.instance = this.componentRef.instance;
    this.instance.data = this.data;
  }
  ngOnChanges(changes: SimpleChanges): void {

  }
}
